/*
 * Copyright 2024 huzheng <huzheng001@gmail.com>
 *
 * This file is part of StarDict.
 *
 * StarDict is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * StarDict is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with StarDict.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "stardict_cal.h"
#include <glib/gi18n.h>
#include <gtk/gtk.h>
#include <stdlib.h>
#include <cstring>
#include <string>

static const StarDictPluginSystemInfo *plugin_info = NULL;
static const StarDictPluginSystemService *plugin_service;
static gint cal_and_ncal;
static IAppDirs* gpAppDirs = NULL;


static void read_func(char *buffer, size_t sizeofbuffer, FILE *pf, std::string &definition)
{
	definition.clear();
	size_t len;
	while (true) {
		len = fread(buffer, 1, sizeofbuffer, pf);
		if (len <= 0)
			break;
		definition.append(buffer, len);
	}
	pclose(pf);

	size_t length1;
	while (true) {
		length1 = definition.length() -1;
		if ((definition[length1] == '\n') || (definition[length1] == ' ')) {
			definition.resize(length1, '\0');
		} else {
			break;
		}
	}
}

static void lookup(const char *text, char ***pppWord, char ****ppppWordData)
{
	bool found_cal = true;
	FILE *pf_cal = NULL;
	if ((cal_and_ncal == 0) || (cal_and_ncal == 2) || (cal_and_ncal == 3)) {
		//gboolean have_cal = g_spawn_command_line_sync("which cal", NULL, NULL, NULL, NULL);  // Always return TRUE.
		int have_cal = system("which cal");
		if (have_cal == 0) {
			pf_cal = popen("cal", "r"); // Always return NOT NULL!
			//if (!pf_cal) {
				//found_cal = false;
			//}
		} else {
			found_cal = false;
		}
	}
	bool found_ncal = true;
	FILE *pf_ncal = NULL;
	if ((cal_and_ncal == 1) || (cal_and_ncal == 2) || (cal_and_ncal == 3)) {
		//gboolean have_ncal = g_spawn_command_line_sync("which ncal", NULL, NULL, NULL, NULL);  // Always return TRUE.
		int have_ncal = system("which ncal");
		if (have_ncal == 0) {
			pf_ncal = popen("ncal", "r"); // Always return NOT NULL!
			//if (!pf_ncal) {
				//found_ncal = false;
			//}
		} else {
			found_ncal = false;
		}
	}
	std::string pango;
	std::string definition;
	char buffer[2048];
	if (cal_and_ncal == 0) {
		if (!found_cal) {
			pango = _("<b><span foreground=\"red\">cal</span> program is not found! Please install it!</b>");		
		} else {
			read_func(buffer, sizeof(buffer), pf_cal, definition);
			plugin_service->terminal2pango(definition.c_str(), pango);			
		}
	} else if (cal_and_ncal == 1) {
		if (!found_ncal) {
			pango = _("<b><span foreground=\"red\">ncal</span> program is not found! Please install it!</b>");
		} else {
			read_func(buffer, sizeof(buffer), pf_ncal, definition);
			plugin_service->terminal2pango(definition.c_str(), pango);			
		}
	} else if (cal_and_ncal == 2) {
		if (!found_cal) {
			pango = _("<b><span foreground=\"red\">cal</span> program is not found! Please install it!</b>");
			pango += "\n";
		} else {
			read_func(buffer, sizeof(buffer), pf_cal, definition);
			definition += "\n";
			plugin_service->terminal2pango(definition.c_str(), pango);
		}
		pango += "\n";
		if (!found_ncal) {
			pango += _("<b><span foreground=\"red\">ncal</span> program is not found! Please install it!</b>");
		} else {
			read_func(buffer, sizeof(buffer), pf_ncal, definition);
			std::string pango2;
			plugin_service->terminal2pango(definition.c_str(), pango2);
			pango += pango2;
		}
	} else {
		if (!found_ncal) {
			pango = _("<b><span foreground=\"red\">ncal</span> program is not found! Please install it!</b>");
			pango += "\n";
		} else {
			read_func(buffer, sizeof(buffer), pf_ncal, definition);
			definition += "\n";
			plugin_service->terminal2pango(definition.c_str(), pango);
		}
		pango += "\n";
		if (!found_cal) {
			pango += _("<b><span foreground=\"red\">cal</span> program is not found! Please install it!</b>");		
		} else {
			read_func(buffer, sizeof(buffer), pf_cal, definition);
			std::string pango2;
			plugin_service->terminal2pango(definition.c_str(), pango2);
			pango += pango2;
		}
	}
	*pppWord = (gchar **)g_malloc(sizeof(gchar *)*2);
	(*pppWord)[0] = g_strdup(text);
	(*pppWord)[1] = NULL;
	*ppppWordData = (gchar ***)g_malloc(sizeof(gchar **)*(1));
	(*ppppWordData)[0] = (gchar **)g_malloc(sizeof(gchar *)*2);
	(*ppppWordData)[0][0] =  plugin_service->build_dictdata('g', pango.c_str());
	(*ppppWordData)[0][1] = NULL;
}

/* concatenate path1 and path2 inserting a path separator in between if needed. */
static std::string build_path(const std::string& path1, const std::string& path2)
{
	std::string res;
	res.reserve(path1.length() + 1 + path2.length());
	res = path1;
	if(!res.empty() && res[res.length()-1] != G_DIR_SEPARATOR)
		res += G_DIR_SEPARATOR_S;
	if(!path2.empty() && path2[0] == G_DIR_SEPARATOR)
		res.append(path2, 1, std::string::npos);
	else
		res.append(path2);
	return res;
}

static std::string get_cfg_filename()
{
	return build_path(gpAppDirs->get_user_config_dir(), "cal.cfg");
}

static void save_conf_file()
{
	gchar *data = g_strdup_printf("[cal]\ncal_and_ncal=%d\n", cal_and_ncal);
	std::string res = get_cfg_filename();
	g_file_set_contents(res.c_str(), data, -1, NULL);
	g_free(data);
}

static void configure()
{
	GtkWidget *window = gtk_dialog_new_with_buttons(_("Cal configuration"), GTK_WINDOW(plugin_info->pluginwin), GTK_DIALOG_MODAL, GTK_STOCK_OK, GTK_RESPONSE_ACCEPT, NULL);
#if GTK_MAJOR_VERSION >= 3
	GtkWidget *vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);
#else
	GtkWidget *vbox = gtk_vbox_new(false, 5);
#endif
	GtkWidget *label;
	//gboolean have_cal;
	//have_cal = g_spawn_command_line_sync("which cal", NULL, NULL, NULL, NULL);  // Always return TRUE.
	int have_cal;
	have_cal = system("which cal");
	if (have_cal == 0) {
		//label = gtk_label_new(NULL);
		//gtk_label_set_markup(GTK_LABEL (label), _("<b><span foreground=\"yellow\">cal</span> program is found!</b>"));
		//gtk_box_pack_start(GTK_BOX(vbox), label, false, false, 0);
	} else {
		label = gtk_label_new(NULL);
		gtk_label_set_markup(GTK_LABEL (label), _("<b><span foreground=\"red\">cal</span> program is not found!</b>"));
		gtk_box_pack_start(GTK_BOX(vbox), label, false, false, 0);
	}
	//gboolean have_ncal;
	//have_ncal = g_spawn_command_line_sync("which ncal", NULL, NULL, NULL, NULL);  // Always return TRUE.
	int have_ncal;
	have_ncal = system("which ncal");
	if (have_ncal == 0) {
		//label = gtk_label_new(NULL);
		//gtk_label_set_markup(GTK_LABEL (label), _("<b><span foreground=\"yellow\">ncal</span> program is found!</b>"));
		//gtk_box_pack_start(GTK_BOX(vbox), label, false, false, 0);
	} else {
		label = gtk_label_new(NULL);
		gtk_label_set_markup(GTK_LABEL (label), _("<b><span foreground=\"red\">ncal</span> program is not found!</b>"));
		gtk_box_pack_start(GTK_BOX(vbox), label, false, false, 0);
	}
	GtkWidget *cal_button = gtk_radio_button_new_with_label(NULL, _("cal."));
	gtk_box_pack_start(GTK_BOX(vbox), cal_button, false, false, 0);
	GtkWidget *ncal_button = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(cal_button), _("ncal."));
	gtk_box_pack_start(GTK_BOX(vbox), ncal_button, false, false, 0);
	GtkWidget *cal_ncal_button = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(cal_button), _("cal and ncal."));
	gtk_box_pack_start(GTK_BOX(vbox), cal_ncal_button, false, false, 0);
	GtkWidget *ncal_cal_button = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(cal_button), _("ncal and cal."));
	gtk_box_pack_start(GTK_BOX(vbox), ncal_cal_button, false, false, 0);
	if (cal_and_ncal == 0) {
		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(cal_button), true);
	} else if (cal_and_ncal == 1) {
		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(ncal_button), true);
	} else if (cal_and_ncal == 2) {
		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(cal_ncal_button), true);
	} else {
		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(ncal_cal_button), true);
	}
	gtk_widget_show_all(vbox);
	gtk_container_add (GTK_CONTAINER (gtk_dialog_get_content_area(GTK_DIALOG(window))), vbox);
	gtk_dialog_run(GTK_DIALOG(window));
	gint new_cal_and_ncal;
	if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(cal_button))) {
		new_cal_and_ncal = 0;
	} else if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(ncal_button))) {
		new_cal_and_ncal = 1;
	} else if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(cal_ncal_button))) {
		new_cal_and_ncal = 2;
	} else {
		new_cal_and_ncal = 3;
	}
	if (new_cal_and_ncal != cal_and_ncal) {
		cal_and_ncal = new_cal_and_ncal;
		save_conf_file();
	}
	gtk_widget_destroy (window);
}

bool stardict_plugin_init(StarDictPlugInObject *obj, IAppDirs* appDirs)
{
	g_debug(_("Loading Cal plug-in..."));
	if (strcmp(obj->version_str, PLUGIN_SYSTEM_VERSION)!=0) {
		g_print(_("Error: Cal plugin version doesn't match!\n"));
		return true;
	}
	obj->type = StarDictPlugInType_VIRTUALDICT;
	obj->info_xml = g_strdup_printf("<plugin_info><name>%s</name><version>2.0</version><short_desc>%s</short_desc><long_desc>%s</long_desc><author>Hu Zheng &lt;huzheng001@gmail.com&gt;</author><website>http://stardict-4.sourceforge.net</website></plugin_info>", _("Cal"), _("Cal virtual dictionary."), _("Show the calendar."));
	obj->configure_func = configure;
	plugin_info = obj->plugin_info;
	plugin_service = obj->plugin_service;
	gpAppDirs = appDirs;

	return false;
}

void stardict_plugin_exit(void)
{
	//save_conf_file();
	gpAppDirs = NULL;
}

bool stardict_virtualdict_plugin_init(StarDictVirtualDictPlugInObject *obj)
{
	std::string res = get_cfg_filename();
	if (!g_file_test(res.c_str(), G_FILE_TEST_EXISTS)) {
		cal_and_ncal = 0;
		g_file_set_contents(res.c_str(), "[cal]\ncal_and_ncal=0\n", -1, NULL);
	} else {
		GKeyFile *keyfile = g_key_file_new();
		g_key_file_load_from_file(keyfile, res.c_str(), G_KEY_FILE_NONE, NULL);
		GError *err = NULL;
		cal_and_ncal = g_key_file_get_integer(keyfile, "cal", "cal_and_ncal", &err);
		if (err) {
			g_error_free (err);
			cal_and_ncal = 0;
		}
		g_key_file_free(keyfile);
	}
	obj->lookup_func = lookup;
	obj->dict_name = _("Calendar");
	obj->author = _("Hu Zheng");
	obj->email = _("huzheng001@gmail.com");
	obj->website = _("http://www.huzheng.org");
	obj->date = _("2024.12.8");
	g_print(_("Cal plug-in \033[31m[loaded]\033[0m.\n"));
	return false;
}
